import { cross } from './darr'

/**
 * 递归删除对象中属性值为空的属性，第二个参数用于定义空的类型
 */
export function removeEmptyField(obj: Record<string, any>, mode?: Array<'[]' | '{}' | 'null' | 'undefined' | '' | '0' | 'false'>) {
    if (!isObject(obj)) {
        return obj
    }

    // 判断空值类型
    let emptyType: Array<'[]' | '{}' | 'null' | 'undefined' | '' | '0' | 'false'> = []
    if (!mode) {
        emptyType = ['{}', '[]', 'null', 'undefined']
    } else {
        emptyType = cross(mode, ['{}', '[]', 'null', 'undefined', '', '0', 'false'])
    }

    function remove(value: Record<string, any>) {
        Object.keys(value).forEach(key => {
            if (
                (emptyType.includes('null') && obj[key] === null) ||
                (emptyType.includes('undefined') && obj[key] === undefined) ||
                (emptyType.includes('[]') && Array.isArray(obj[key]) && obj[key].length === 0) ||
                (emptyType.includes('') && obj[key] === '') ||
                (emptyType.includes('0') && obj[key] === 0) ||
                (emptyType.includes('false') && obj[key] === false) ||
                (emptyType.includes('{}') && isObject(obj[key]) && Object.keys(obj[key]).length === 0)
            ) {
                delete obj[key]
            }

            if (isObject(obj[key])) {
                const result = removeEmptyField(obj[key], mode) as Record<string, any>
                if (emptyType.includes('{}') && Object.keys(result).length === 0) {
                    delete obj[key]
                }
            }
        })

        return value
    }

    return remove(obj)
}

/**
 * 判断是否为对象字面量
 */
export function isObject(value: any): boolean {
    return Object.prototype.toString.call(value) === '[object Object]'
}

/**
 * 判断是否为空对象字面量 {} 
 */
export function isEmptyObject(value: any): boolean {
    return isObject(value) && Object.keys(value).length === 0
}

export default {
    removeEmptyField,
    isObject,
    isEmptyObject,
}